package grpc

import (
	"geak/api/service/lottery"
	"geak/api/service/middleware/auth"
	"geak/api/service/middleware/cred"
	"geak/api/service/middleware/recovery"
	"geak/api/service/middleware/zap"
	grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
	grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
	"log"

	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"

	gateway_lottery "geak/biz/lottery"
	"geak/libs/conf"
	"google.golang.org/grpc"
	"net"
)

var (
	lotterySrv *lottery.Service
)

func Init(c *conf.Config){

	initService(c)
	lis,err := net.Listen("tcp", ":443")
	if err != nil {
		panic(err)
	}
	s := grpc.NewServer(cred.TLSInterceptor(),
		grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
				grpc_recovery.StreamServerInterceptor(recovery.RecoveryInterceptor()),
				grpc_zap.StreamServerInterceptor(zap.ZapInterceptor()),
				grpc_auth.StreamServerInterceptor(auth.AuthInterceptor),
			)),
		grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
				grpc_recovery.UnaryServerInterceptor(recovery.RecoveryInterceptor()),
				grpc_zap.UnaryServerInterceptor(zap.ZapInterceptor()),
				grpc_auth.UnaryServerInterceptor(auth.AuthInterceptor),
			)),
		)
	route(s)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("grpcServer.Serve err: %v", err)
	}

}

func initService(c *conf.Config){
	lotterySrv = lottery.New(c)
}

func route(s *grpc.Server) {
	gateway_lottery.RegisterLotteryServer(s,&Lottery{})
}